import streamlit as st
import streamlit_authenticator as stauth
import datetime as dt
import yaml
from streamlit_echarts import st_pyecharts
import plotly.figure_factory as ff


import ToolBox as tb


def init():
    st.set_page_config(
        page_title="哨兵数据中心", 
        page_icon='🇨🇳', 
        layout="wide", # "centered" or "wide"
        initial_sidebar_state="auto", # "auto", "expanded", or "collapsed"
        menu_items={
            'Get Help': 'https://www.extremelycoolapp.com/help',
            'Report a bug': "https://www.extremelycoolapp.com/bug",
            'About': "# This is a header. This is an *extremely* cool app!"
        })
    st.session_state.cargs = {
        "database":"henan_rsanalysis",
        "user":"postgres",
        "password":"postgresql",
        "host":"192.168.1.71", 
        "port":"5432"
        }
    st.session_state.config_file = 'config.yaml'
    return


def login():
    
    with open(st.session_state.config_file) as file_handle:
        st.session_state.config = yaml.load(file_handle, Loader=yaml.loader.SafeLoader)
    st.session_state.authenticator = stauth.Authenticate(
        st.session_state.config['credentials'],
        st.session_state.config['cookie']['name'],
        st.session_state.config['cookie']['key'],
        st.session_state.config['cookie']['expiry_days'],
        st.session_state.config['pre-authorized']
        )
    if not st.session_state["authentication_status"]:
       
        st.session_state.login_col = st.columns([5,3,5])[1]
        with st.session_state.login_col:
            st.header(':blue[Home] :sunglasses:',divider='rainbow')
            tab1,tab2,tab3=st.tabs(["登录","注册","找回"])
        with tab1:
            st.session_state.authenticator.login(
                location='main', # {'main', 'sidebar'}
                max_concurrent_users=10, # int, default None
                fields={
                    'Form name':'Login', 
                    'Username':'Username', 
                    'Password':'Password', 
                    'Login':'Login'},
                clear_on_submit=False, # bool, default False
                )
        with tab2:
            try:
                registered_userr = st.session_state.authenticator.register_user(pre_authorization=False)
                if registered_userr[0]:
                    st.success('User registered successfully')
            except Exception as e:
                st.error(e)
        with tab3:
            with st.container():  # border=True
                try:
                    forgotten_password, _, _ = st.session_state.authenticator.forgot_password()
                    if forgotten_password:
                        st.success('New password to be sent securely')
                        # The developer should securely transfer the new password to the user.
                    elif forgotten_password == False:
                        st.error('Username not found')
                except Exception as e:
                    st.error(e)
                try:
                    forgotten_username, _ = st.session_state.authenticator.forgot_username()
                    if forgotten_username:
                        st.success('Username to be sent securely')
                        # The developer should securely transfer the username to the user.
                    elif forgotten_username == False:
                        st.error('Email not found')
                except Exception as e:
                    st.error(e) 

    return


def work():
   
    tiles = tb.province_2_tiles(
        st.session_state.cargs,
        st.session_state.province)
    st.session_state.df = tb.pgsql_2_info(
        st.session_state.cargs,
        tiles,
        st.session_state.sdate,
        st.session_state.edate,
        st.session_state.clouds[1],)
        
    tab1,tab2,tab3 = st.tabs(["🗃 Table:red","📈 Chart:blue", ":1234: details:blue"])
    
    with tab1:
        st.data_editor(
            st.session_state.df,
            width=None, 
            height=800, 
            use_container_width=True, 
            hide_index=False, 
            column_order=st.session_state.df.columns.tolist(), 
            column_config=None, 
            num_rows="fixed", # "fixed" or "dynamic"
            disabled=False, 
            key='data_table', 
            on_change=None, 
            args=None, 
            kwargs=None)

    with tab2:
        data = st.session_state.df["date"].value_counts()
        st.bar_chart(
            data=data,
            # x='49SGR', 
            # y='date', 
            # color='white', 
            width=0, 
            height=700, 
            use_container_width=True)
      
    with tab3:
        pass

    with st.popover(
        label=':sparkles:',
        help=None, 
        disabled=False, 
        use_container_width=True):
        st.markdown("Hello World 👋")
        name = st.text_input("What's your name?")
    return


def sidebar():
    with st.sidebar:
        with st.form("my_form"):
            # st.caption('This is a string that explains something above.')
            st.selectbox(
                label='省份', 
                options=tb.get_proginces(st.session_state.cargs), 
                index=32, 
                # format_func=special_internal_function, 
                key='province', 
                help='选择需要查询的省份', 
                on_change=None, 
                args=None, 
                kwargs=None, 
                placeholder="Choose an option", 
                disabled=False, 
                label_visibility="visible")
            
            st.date_input(
                label='起始日期', 
                value=dt.datetime.strptime('2024-03-01','%Y-%m-%d').date(),  #"default_value_today", 
                min_value=dt.datetime.strptime('2018-01-03','%Y-%m-%d').date(), 
                max_value=dt.date.today(), 
                key='sdate', 
                help='选择影像起始日期', 
                on_change=None, 
                args=None, 
                kwargs=None,
                format="YYYY/MM/DD", 
                disabled=False, 
                label_visibility="visible")
            
            st.date_input(
                label='结束日期', 
                value=dt.date.today(),
                min_value=st.session_state.sdate, 
                max_value=dt.date.today(), 
                key='edate', 
                help='选择影像截至日期', 
                on_change=None, 
                args=None, 
                kwargs=None,
                format="YYYY/MM/DD", 
                disabled=False, 
                label_visibility="visible")
            
            st.slider(
                label='云量', 
                min_value=0.0, 
                max_value=100.0,
                step=1.0,
                value=(0.0,100.0), 
                # format_func=special_internal_function, 
                key='clouds', 
                help='选择最大含云量', 
                on_change=None, 
                args=None, 
                kwargs=None,
                disabled=False, 
                label_visibility="visible")
            
            st.toggle(
                label='全选', 
                value=False, 
                key='toggle', 
                help='默认全选哨兵数据', 
                on_change=None, 
                args=None, 
                kwargs=None, 
                disabled=False, 
                label_visibility="visible")
            
            st.session_state.submitted = st.form_submit_button("查询")

    return


def main():
    
    init()
    
    login()
    
    if st.session_state["authentication_status"]:
        sidebar()
        st.session_state.authenticator.logout(
            button_name='Logout',
            location='sidebar',  #  {'main', 'sidebar','unrendered'}, default 'main'
            key=None,
            )
    elif st.session_state["authentication_status"] is False:
        # with st.session_state.login_col:
        st.session_state.login_col.error('Username/password is incorrect')
    elif st.session_state["authentication_status"] is None:
        st.session_state.login_col.warning('Please enter your username and password')
    
    if st.session_state.submitted: 
        work()
    
    # if st.session_state.hover_tabs =='哨兵数据中心':
    # st.title("Navigation Bar")
    # st.write('Name of option is')
    

    return


# streamlit run App.py
main()